package com.ccteam.fluidmusic.ui.local.artist

import android.app.Application
import android.support.v4.media.MediaBrowserCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.ccteam.fluidmusic.ui.PARENT_ID_KEY
import com.ccteam.fluidmusic.fluidmusic.common.MusicServiceConnectionFlow
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/2/9
 *
 * 本地歌手详情页ViewModel
 **/
@HiltViewModel
class LocalArtistDetailViewModel @Inject constructor(
    private val musicServiceConnectionFlow: MusicServiceConnectionFlow,
    application: Application,
    savedStateHandle: SavedStateHandle
): AndroidViewModel(application) {

    private var parentId: String? = null

    private val _artistDetailParentIds = MutableLiveData<List<Pair<String,String>>>()
    val artistDetailParentIds: LiveData<List<Pair<String,String>>> = _artistDetailParentIds

    /**
     * 订阅回调处理
     */
    private val subscriptionCallback = object : MediaBrowserCompat.SubscriptionCallback() {
        override fun onChildrenLoaded(
            parentId: String,
            children: List<MediaBrowserCompat.MediaItem>
        ) {
            _artistDetailParentIds.value = children.map {
                Pair(it.mediaId!!, it.description.title.toString())
            }
        }
    }

    init {
        savedStateHandle.get<String>(PARENT_ID_KEY)?.let {
            this.parentId = it
            musicServiceConnectionFlow.subscribe(it,subscriptionCallback)
        }
    }

    override fun onCleared() {
        super.onCleared()
        parentId?.let {
            musicServiceConnectionFlow.unsubscribe(it,subscriptionCallback)
        }
    }
}